package com.knife.news.manage.action;

import java.io.File;
import java.io.IOException;
import java.io.StringReader;
import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;

import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.TokenStream;
import org.apache.lucene.analysis.tokenattributes.CharTermAttribute;
import org.jsoup.Jsoup;
import org.jsoup.helper.StringUtil;
import org.jsoup.nodes.Document;
import org.wltea.analyzer.lucene.IKAnalyzer;

import com.knife.news.logic.FieldsService;
import com.knife.news.logic.FormService;
import com.knife.news.logic.NewsService;
import com.knife.news.logic.SiteService;
import com.knife.news.logic.Type2Service;
import com.knife.news.logic.TypeService;
import com.knife.news.logic.impl.FieldsServiceImpl;
import com.knife.news.logic.impl.FlowNodeServiceImpl;
import com.knife.news.logic.impl.FlowServiceImpl;
import com.knife.news.logic.impl.FormServiceImpl;
import com.knife.news.logic.impl.NewsServiceImpl;
import com.knife.news.logic.impl.NewsVersionServiceImpl;
import com.knife.news.logic.impl.SiteServiceImpl;
import com.knife.news.logic.impl.Type2ServiceImpl;
import com.knife.news.logic.impl.TypeServiceImpl;
import com.knife.news.model.Fields;
import com.knife.news.model.Form;
import com.knife.news.object.FlowNode;
import com.knife.news.object.FormField;
import com.knife.news.object.Keywords;
import com.knife.news.object.Logs;
import com.knife.news.object.News;
import com.knife.news.object.NewsVersion;
import com.knife.news.object.Site;
import com.knife.news.object.Type;
import com.knife.news.object.Type2;
import com.knife.news.object.User;
import com.knife.operation.sort.KeywordsWeightComparator;
import com.knife.util.CommUtil;
import com.knife.web.ActionContext;
import com.knife.web.Globals;
import com.knife.web.Module;
import com.knife.web.Page;
import com.knife.web.WebForm;

public class NewsManageAjaxAction extends ManageAction {
	private NewsService newsDAO = NewsServiceImpl.getInstance();
	private FieldsService fieldDAO = FieldsServiceImpl.getInstance();
	private NewsVersionServiceImpl newsvDao = NewsVersionServiceImpl.getInstance();
	
	private Type2Service type2DAO = Type2ServiceImpl.getInstance();
	private TypeService typeDAO = TypeServiceImpl.getInstance();
	private SiteService siteDAO = SiteServiceImpl.getInstance();
	private FieldsService fieldsDAO = FieldsServiceImpl.getInstance();
	private FormService formDAO = FormServiceImpl.getInstance();
	private String tid = "";
	private String tidv = "";
	private Date nowDate=new Date();
	private FlowServiceImpl flowDao=FlowServiceImpl.getInstance();
	private FlowNodeServiceImpl flowNodeDao = FlowNodeServiceImpl.getInstance();
	private String flow;
	private String node;
	private Type aType;
	
	public Page doAdd(WebForm form, Module module) {
		return module.findPage("ajax");
	}

	public Page doGetKeywords(WebForm form, Module module) {
		String content = CommUtil.null2String(form.get("content"));
		ArrayList<Keywords> keywords = new ArrayList<Keywords>();
		String ret = "";
		if (content.length() > 0) {
			Document htmdoc = Jsoup.parse(content);
			Analyzer analyzer = new IKAnalyzer();
			TokenStream ts=null;
			try {
				ts = analyzer.tokenStream(null,new StringReader(htmdoc.text()));
			} catch (IOException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}
			// TypeAttribute typeAtt = (TypeAttribute)
			// ts.getAttribute(TypeAttribute.class);
			CharTermAttribute termAtt = ts
					.getAttribute(CharTermAttribute.class);
			try {
				while (ts.incrementToken()) {
					String aValue = termAtt.toString();
					if (aValue.length() > 1) {
						Keywords akey = new Keywords();
						akey.setWeight(0);
						akey.setValue(termAtt.toString());
						for (Keywords key : keywords) {
							if (aValue.equals(key.getValue())) {
								akey.setWeight(key.getWeight() + 1);
								keywords.remove(key);
								break;
							}
						}
						if (!StringUtil.isNumeric(akey.getValue())){
							keywords.add(akey);
						}
					}
				}
				for (int i=0;i<keywords.size();i++) {
					Keywords key=keywords.get(i);
					if (key.getWeight() <= 1) {
						keywords.remove(key);
					}
				}
				Collections.sort(keywords, new KeywordsWeightComparator());
				for (Keywords key : keywords) {
					ret += key.getValue() + ",";
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		if (ret.length() > 0) {
			ret = ret.substring(0, ret.length() - 1);
		}
		form.addResult("jvalue", ret);
		return module.findPage("ajax");
	}

	public Page doGetOrderNewsId(WebForm form, Module module) {
		int order = CommUtil.null2Int(form.get("neworder"));
		String typeid = CommUtil.null2String(form.get("tid"));
		int totalnums = newsDAO.getSum(-1, "", typeid, "", "", "");
		String sql = "k_type=? and k_order=?";
		List<Object> paras = new ArrayList<Object>();
		paras.add(typeid);
		paras.add(totalnums - order);
		// System.out.println("_____查询交换的文章:"+sql+":::"+totalnums+"::::"+order);
		List<News> news = newsDAO.getNews(sql, paras);
		if (news.size() > 0) {
			News anews = news.get(0);
			form.addResult("jvalue", anews.getId());
		}
		return module.findPage("ajax");
	}

	public Page doOrder(WebForm form, Module module) {
		String oldId = CommUtil.null2String(form.get("oOrder"));
		String newId = CommUtil.null2String(form.get("nOrder"));
		String typeid = CommUtil.null2String(form.get("tid"));
		// String treeid = CommUtil.null2String(form.get("treeid"));
		if (typeid.equals("")) {
			typeid = "0";
		}
		if (oldId.equals("") && newId.equals("")) {
			return null;
		} else {
			News oldNews;
			News newNews;
			if (oldId.equals("")) {
				newNews = newsDAO.getNewsById(newId);
				oldNews = newNews.getPrevNews();
			} else if (newId.equals("")) {
				oldNews = newsDAO.getNewsById(oldId);
				newNews = oldNews.getNextNews();
			} else {
				oldNews = newsDAO.getNewsById(oldId);
				newNews = newsDAO.getNewsById(newId);
			}
			// newNews=newsdao.getNewsById(newId);
			int oldOrder = oldNews.getOrder();
			int newOrder = newNews.getOrder();
			if (oldOrder > 0 && newOrder > 0) {
				newsDAO.reArrange(typeid, oldOrder, newOrder);
			}
		}
		return null;
	}

	// 重置排序数据
	public Page doResetOrder(WebForm form, Module module) {
		String typeid = CommUtil.null2String(form.get("tid"));
		if (typeid.length() > 0) {
			String sql = "k_type=? order by length(k_order),k_order";
			List<Object> paras = new ArrayList<Object>();
			paras.add(typeid);
			List<News> news = newsDAO.getNews(sql, paras);
			for (int i = 0; i < news.size(); i++) {
				News anews = news.get(i);
				anews.setOrder(i + 1);
				newsDAO.updateNews(anews);
			}
		}
		return null;
	}

	/*
	 * jlm
	 * news_version list
	 */
	public Page doNewsVersion(WebForm form,Module module){
		String newsid = CommUtil.null2String(form.get("newsid"));
		//String tid = CommUtil.null2String(form.get("tid"));
		
		News news=newsDAO.getNewsById(newsid);
		Type atype=typeDAO.getTypeById(news.getType());
		
		if(news.getLink()!=null && news.getLink().length()>0){
			form.addResult("msg", "该文章为引用文章，不可编辑文章版本！");
			return module.findPage("ajax");
		}else{
			//if(atype.getFlow()==null && ){
				
			//}else{
			List<NewsVersion> versionList=newsvDao.getNewsVersionByNewsid(newsid);
			
			form.addResult("versionList", versionList);
			form.addResult("news", news);
			return module.findPage("version");
			//}
		}
	}
	/*
	 * jlm
	 * news_version add 
	 */
	public void doAddNewsVersion(WebForm form,Module module) throws UnsupportedEncodingException{
		String newsid = CommUtil.null2String(form.get("newsid"));
		News news=newsDAO.getNewsById(newsid);
		
		String description = CommUtil.null2String(form.get("description"));
		//String des=java.net.URLDecoder.decode(description,"utf-8");
		NewsVersion newsv = new NewsVersion(news);
		newsv.setNewsid(newsid);
		newsv.setDescription(description);
		
		int num=newsvDao.getNewsVersionByNewsid(newsid).size();
		newsv.setVersionnumber(num+1);
		
		newsvDao.saveNewsVersion(newsv);
		
		
		doNewsVersion(form,module);
	}
	
	/*
	 * jlm
	 * news_version del
	 */
	public void doDelNewsVersion(WebForm form,Module module){
		String versionid = CommUtil.null2String(form.get("versionid"));
		String newsid = CommUtil.null2String(form.get("newsid"));
		
		NewsVersion anewsv = newsvDao.getNewsVersionById(versionid);
		List<NewsVersion> vlist=newsvDao.getNewsVersionByNewsid(newsid);
		int num=newsvDao.getNewsVersionByNewsid(newsid).size();
		if(anewsv.getVersionnumber()==num){
			newsvDao.delNewsVersion(anewsv);
		}else{
			for(int i=anewsv.getVersionnumber(); i<num;i++){
				//int index=i-1;
				NewsVersion av=vlist.get(i);
				av.setVersionnumber(i);
				newsvDao.updateNewsVersion(av);
			}
		}
		newsvDao.delNewsVersion(anewsv);
		doNewsVersion(form,module);
	}
	
	/*
	 * jlm
	 * news_version back
	 */
	public void doBackNewsVersion(WebForm form,Module module){
		String versionid = CommUtil.null2String(form.get("versionid"));
		String newsid = CommUtil.null2String(form.get("newsid"));
		
		NewsVersion anewsv = newsvDao.getNewsVersionById(versionid);
		News xnew = new News(anewsv);
		newsDAO.updateNews(xnew);
		
		doNewsVersion(form,module);
	}
	
	public Page doNoDisplay(WebForm form, Module module) {
		String newsid = CommUtil.null2String(form.get("newsid"));
		String versionid = CommUtil.null2String(form.get("versionid"));
		News news = newsDAO.getNewsById(newsid);
		news.setDisplay(0);
		newsDAO.updateNews(news);
		form.addResult("msg", "取消审核！");
		news.updatePub();
	
		Logs log=new Logs("["+user.getUsername()+"]" + "撤销文章:"+news.getTitle());
		logDAO.saveLogs(log);
		return doEditNewsVersion(form, module);
	}
	
	public Page doSave(WebForm form, Module module) {
		String newsid = CommUtil.null2String(form.get("newsid"));
		String versionid = CommUtil.null2String(form.get("versionid"));
		
		
		String id ="";
		String linkTypes = CommUtil.null2String(form.get("linkTypes"));
		String otherTypes = CommUtil.null2String(form.get("otherTypes"));
		String date = CommUtil.null2String(form.get("date"));
		String offdate = CommUtil.null2String(form.get("offdate"));
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		Date startDate;
		Date endDate;
		try {
			startDate = sdf.parse(date);
		} catch (Exception e) {
			startDate = nowDate;
		}
		try{
			endDate = sdf.parse(offdate);
		}catch(Exception e){
			endDate = null;
		}
		News fnews = (News) form.toPo(News.class);
		fnews.setDate(startDate);
		fnews.setOffdate(endDate);
		//检查用户身份并附权限
		
		// 首先先判断下是否使用了发文工作流并查看工作流是否已啟動
		if (user.getPopedom() !=1) {// 只在编辑文章时才创建文章审核需要的人，fnews.setFlowusers
			Type type = typeDAO.getTypeById(fnews.getType());
			if (type.getFlow() != null && type.getFlow() != ""
					&& flowDao.getFlowById(type.getFlow()) != null
					&& flowDao.getFlowById(type.getFlow()).getStatus() == 1) {
				List<FlowNode> nodelist = new ArrayList<FlowNode>();
				nodelist = flowNodeDao.getFlowNodeByFlowId(type.getFlow());
				for (int i = 0; nodelist != null && i < nodelist.size(); i++) {
					if (nodelist.get(i).getType() == 2 && nodelist.get(i).getExecute_type()==2) {// 2表示审核文章 ，1表示编辑文章
						int pop = CommUtil.null2Int(nodelist.get(i)
								.getExecutor());
						String sql = "k_popedom=1";
						List<User> userlist = userDAO.getUsersBySql(sql);
						String userid = "";
						for (int j = 0; userlist != null && j < userlist.size(); j++) {
							userid += userlist.get(j).getId().toString() + ",";
						}
						fnews.setFlowusers(userid);
					}
				}
			}
		}
		if (user.getPopedom() == 1) {

			// workflow
			Type type = typeDAO.getTypeById(fnews.getType());
			if (type.getFlow() != null && type.getFlow() != ""
					&& flowDao.getFlowById(type.getFlow()) != null
					&& flowDao.getFlowById(type.getFlow()).getStatus() == 1) {
				List<FlowNode> nodelist1 = new ArrayList<FlowNode>();
				nodelist1 = flowNodeDao.getFlowNodeByFlowId(type.getFlow());
				for (int i = 0; nodelist1 != null && i < nodelist1.size(); i++) {
					int lei=nodelist1.get(i).getType();
					if (nodelist1.get(i).getType() == 2) {
						if (nodelist1.get(i).getExecute_type() == 1) {
							fnews.setDisplay(1);
						} else {
							if (nodelist1.get(i).getExecute_type() == 2) {
								String ids = fnews.getFlowusers();
								String[] uid = ids.split(",");
								String latest = "";
								for (int k = 0; uid != null && k < uid.length; k++) {
									if (uid[k] != user.getId()) {
										latest += uid[k] + ",";
									}
								}
								fnews.setFlowusers(latest);
								if (latest == "") {
									fnews.setDisplay(1);
									form.addResult("msg", "该文章审核成功！");
								} else {

									form.addResult("msg",
											"本次审核成功，但还需要其他人的审核才能最终审核该文章！");
								}
								
							}
						}// end else
					}
				}

			} else {
				fnews.setDisplay(1);
			}

			// end workflow
			// fnews.setDisplay(1);
		}
		id = newsDAO.addNews(fnews);
		
		tid = fnews.getType();
		News news=new News();
		if (id.length()>0) {
			//news.setId(id);
			news=newsDAO.getNewsById(id);
			// 保存自定义表单
			aType = typeDAO.getTypeById(news.getType());
			if (aType.getForm() != null) {
				String formId = aType.getForm();
				if (formId.length() > 0) {
					try{
						Form aform = formDAO.getFormById(formId);
						// System.out.println("取得的表单ID是:"+ids[i]);
						List<FormField> formFields = fieldsDAO.jsonStringToList(
								news.getId(), aform.getContent());
						saveUserForm(form, formFields, formId, news.getId());
						// form.addResult("fieldList", formFields);
					}catch(Exception e){
						System.out.println("自定义表单查找异常:"+e.getMessage());
					}
				}
			}
			// 新闻的引用
			if (!linkTypes.equals("")) {
				String[] typeids = linkTypes.split(",");
				for (int i = 0; i < typeids.length; i++) {
					News anew = new News();
					anew.setTitle(news.getTitle());
					// anew.setFile(news.getFile());
					anew.setLink(news.getId());
					anew.setType(typeids[i]);
					anew.setContent("<p>&nbsp;</p>");
					anew.setCommend("0");
					anew.setDisplay(news.getDisplay());
					anew.setDate(news.getDate());
					newsDAO.saveNews(anew);
				}
			}
			if(aType!=null){
				news.updatePub();
			}
			// 新闻的分发
			if (!otherTypes.equals("")) {
				String[] typeids = otherTypes.split(",");
				for (int i = 0; i < typeids.length; i++) {
					News anew = news;
					com.knife.news.model.News bnews = new com.knife.news.model.News();
					anew.setId(bnews.getId());
					anew.setType(typeids[i]);
					//News anew = new News(bnews);
					addNews(anew, form);
				}
			}
			//workflow
			//end workflow
			form.addResult("msg", "发布成功！");
		} else {
			form.addResult("msg", "发布失败,请检查权限和日志！");
		}
		return doEditNewsVersion(form, module);
	}

	public Page doUpdate(WebForm form, Module module) {
		
		String newsid = CommUtil.null2String(form.get("newsid"));
		String versionid = CommUtil.null2String(form.get("versionid"));
		
		
		News news = (News) form.toPo(News.class);
		String date = CommUtil.null2String(form.get("date"));
		String offdate = CommUtil.null2String(form.get("offdate"));
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		Date startDate;
		Date endDate;
		try {
			startDate = sdf.parse(date);
		} catch (Exception e) {
			startDate = nowDate;
		}
		try{
			endDate = sdf.parse(offdate);
		}catch(Exception e){
			endDate = null;
			//GregorianCalendar gc =new GregorianCalendar();
			//gc.setTime(startDate);
			//gc.add(1, 10);
			//endDate = gc.getTime();
		}
		news.setDate(startDate);
		if(endDate!=null){
			news.setOffdate(endDate);
		}
		tid = news.getType();
		form.addResult("tid", tid);
		//检查用户身份并附权限
		int flowflag=0;
		int p = user.getPopedom();
		if (user.getPopedom() == 1) {
			// flow
			if (news.getDisplay() == 1) {
				Collection<Object> pa = new ArrayList<Object>();
				String sqlflow = "";
				pa.add(typeDAO.getTypeById(tid).getFlow());
				sqlflow = "id=? and k_status='1'";
				if (flowDao.getFlowBySql(sqlflow, pa, 0, -1).size() > 0) {
					List<FlowNode> nodelist1 = new ArrayList<FlowNode>();
					nodelist1 = flowNodeDao.getFlowNodeByFlowId(typeDAO
							.getTypeById(tid).getFlow());
					for (int i = 0; nodelist1 != null && i < nodelist1.size(); i++) {
						int lei = nodelist1.get(i).getType();
						if (nodelist1.get(i).getType() == 2) {
							if (nodelist1.get(i).getExecute_type() == 1) {
								news.setDisplay(1);
							} else {
								if (nodelist1.get(i).getExecute_type() == 2) {
									// 怎么实现所有人都审核过，文章才算审核 了呢？？？？？

									String ids = news.getFlowusers();
									String[] uid = ids.split(",");
									String latest = "";
									for (int k = 0; uid != null
											&& k < uid.length; k++) {
										String userid = user.getId();
										if (!uid[k].equals(user.getId())) {
											latest += uid[k] + ",";
										}
									}
									news.setFlowusers(latest);
									if (latest == "") {
										news.setDisplay(1);
										form.addResult("msg", "该文章审核成功！");
									} else {
										news.setDisplay(0);
										form.addResult("msg",
												"本次审核成功，但还需要其他人的审核才能最终审核该文章！");
										flowflag = 1;
									}

								}
							}// end else
						}
					}

				} else {
					news.setDisplay(1);
				}
			}
			// end flow
			// news.setDisplay(1);
		}
		if (newsDAO.updateNews(news)) {
			//保存自定义表单
			Type aType = typeDAO.getTypeById(news.getType());
			if (aType.getForm() != null) {
				String formId = aType.getForm();
				if (formId.length() > 0) {
					try{
						Form aform = formDAO.getFormById(formId);
						// System.out.println("取得的表单ID是:"+formId);
						List<FormField> formFields = fieldsDAO.jsonStringToList(
								news.getId(), aform.getContent());
						updateUserForm(form, formFields, formId, news.getId());
						// form.addResult("fieldList", formFields);
					}catch(Exception e){
						System.out.println("自定义表单查找异常:"+e.getMessage());
					}
				}
			}
			//生成html页面
			news.updatePub();
			//记录日志
			Logs log=new Logs("["+user.getUsername()+"]"+"编辑文章:"+news.getTitle());
			logDAO.saveLogs(log);
			if(flowflag==0){
			form.addResult("msg", "更新成功！");
			}else{
				form.addResult("msg", "本次审核成功，但还需要其他人的审核才能最终审核该文章！");
			}
		} else {
			Logs log=new Logs("["+user.getUsername()+"]"+"编辑文章失败:"+news.getTitle());
			logDAO.saveLogs(log);
			form.addResult("msg", "更新失败！");
		}
		return doEditNewsVersion(form, module);
	}

	private boolean addNews(News news, WebForm form) {
		String logstr="保存";
		if(user.getPopedom()==0){
			logstr="保存";
		}else if(user.getPopedom()==1){
			logstr="审核";
		}else{
			logstr="发布";
		}
		boolean ret = newsDAO.saveNews(news);
		if (ret) {
			// System.out.println("在保存之后ID是否已生成："+news.getId());
			// 保存自定义表单
			Type aType = typeDAO.getTypeById(news.getType());
			if (aType.getForm() != null) {
				String formId = aType.getForm();
				if (formId.length() > 0) {
					Form aform = formDAO.getFormById(formId);
					// System.out.println("取得的表单ID是:"+ids[i]);
					List<FormField> formFields = fieldsDAO.jsonStringToList(
							news.getId(), aform.getContent());
					saveUserForm(form, formFields, formId, news.getId());
					// form.addResult("fieldList", formFields);
				}
			}
			//记录日志
			Logs log=new Logs("["+user.getUsername()+"]"+ logstr + "文章:"+news.getTitle());
			logDAO.saveLogs(log);
		}else{
			//记录日志
			Logs log=new Logs("["+user.getUsername()+"]"+ logstr + "文章失败:"+news.getTitle());
			logDAO.saveLogs(log);
		}
		return ret;
	}
	private void saveUserForm(WebForm form, List<FormField> formFields,
			String formid, String newsid) {
		for (FormField formField : formFields) {
			Fields afield = new Fields();
			afield.setFormid(formid);
			afield.setName(formField.getName());
			afield.setNewsid(newsid);
			afield.setOrder(formField.getOrder());
			afield.setValue(CommUtil.null2String(form.get("u_"
					+ formField.getName())));
			fieldsDAO.saveFields(afield);
			
		}
	}
	private void updateUserForm(WebForm form, List<FormField> formFields,
			String formid, String newsid) {
		for (FormField formField : formFields) {
			Fields afield = fieldsDAO.getFieldsByNews(newsid,
					formField.getOrder());
			/*
			 * if(formField.getType().equals("file")){ form =
			 * uploadFile(form,"u_"
			 * +formField.getName(),"upload_"+formField.getName()); }
			 */
			if (afield != null) {
				afield.setFormid(formid);
				afield.setName(formField.getName());
				afield.setNewsid(newsid);
				afield.setOrder(formField.getOrder());
				afield.setValue(CommUtil.null2String(form.get("u_"
						+ formField.getName())));
				fieldsDAO.updateFields(afield);
			} else {
				afield = new Fields();
				afield.setFormid(formid);
				afield.setName(formField.getName());
				afield.setNewsid(newsid);
				afield.setOrder(formField.getOrder());
				afield.setValue(CommUtil.null2String(form.get("u_"
						+ formField.getName())));
				fieldsDAO.saveFields(afield);
			}
			//System.out.println("成功更新字段值:" + formField.getName() + ";字段的值是:"+ form.get("u_" + formField.getName()));
		}
	}

	/*
	 * jlm
	 * news_version back
	 */
	public Page doEditNewsVersion(WebForm form,Module module){
		String versionid = CommUtil.null2String(form.get("versionid"));
		String newsid = CommUtil.null2String(form.get("newsid"));
		
		NewsVersion newsv = newsvDao.getNewsVersionById(versionid);
		News news =newsDAO.getNewsById(newsid);
		
		
		form.addResult("newsv", newsv);
		
		
		List<Type> typeList = new LinkedList<Type>();
		List<Type2> type2List = type2DAO.getAllTypes();
		List<Type> typeListv = new LinkedList<Type>();
		List<Type2> type2Listv = type2DAO.getAllTypes();
		tid = CommUtil.null2String(news.getType());
		tidv = CommUtil.null2String(newsv.getType());
		
		
		if (!tidv.equals("") && tidv.indexOf(",") < 0) {
			Type aTypev = typeDAO.getTypeById(tidv);
			if(aTypev!=null){
			if(aTypev.getSite()!=null){
				Site site = siteDAO.getSiteById(aTypev.getSite());
//				if(site!=null){
//					//form.addResult("sid", aType.getSite());
//					if(site.getHtml()==1){
//						ActionContext.getContext().getSession().setAttribute("site_dir", site.getPub_dir());
//						if(site.getBig5()==1){
//							ActionContext.getContext().getSession().setAttribute("big5_dir", site.getPub_dir()+"/big5");
//						}
//					}
//					form.addResult("thisSite", site);
//				}
			}
			if (popedom > 0) {
				typeListv = typeDAO.getSubTypesById(aTypev.getParent());
			} else {
				typeListv = typeDAO.getRightSubTypesById(aTypev.getParent(),
						user.getId());
			}
			form.addResult("tidv", tidv);
			form.addResult("tnamev", aTypev.getName());
			// 取得自定义表单
			if (aTypev.getForm() != null) {
				String formId = aTypev.getForm();
				if (formId.length() > 0) {
					try{
						Form aform = formDAO.getFormById(formId);
						// System.out.println("取得的表单ID是:"+formId);
						List<FormField> formFields = fieldsDAO.jsonStringToList(
								newsv.getId(), aform.getContent());
						form.addResult("fieldListv", formFields);
					}catch(Exception e){
						System.out.println("自定义表单查找异常:"+e.getMessage());
					}
				}
			}
			}else{
				form.addResult("tnamev", "无频道");
			}
		}
		
		//System.out.println("取得的类别ID是:"+tid);
		if (!tid.equals("") && tid.indexOf(",") < 0) {
			Type aType = typeDAO.getTypeById(tid);
			if(aType!=null){
			if(aType.getSite()!=null){
				Site site = siteDAO.getSiteById(aType.getSite());
				if(site!=null){
					//form.addResult("sid", aType.getSite());
					if(site.getHtml()==1){
						ActionContext.getContext().getSession().setAttribute("site_dir", site.getPub_dir());
						if(site.getBig5()==1){
							ActionContext.getContext().getSession().setAttribute("big5_dir", site.getPub_dir()+"/big5");
						}
					}
					form.addResult("thisSite", site);
				}
			}
			if (popedom > 0) {
				typeList = typeDAO.getSubTypesById(aType.getParent());
			} else {
				typeList = typeDAO.getRightSubTypesById(aType.getParent(),
						user.getId());
			}
			form.addResult("tid", tid);
			form.addResult("tname", aType.getName());
			// 取得自定义表单
			if (aType.getForm() != null) {
				String formId = aType.getForm();
				if (formId.length() > 0) {
					try{
						Form aform = formDAO.getFormById(formId);
						// System.out.println("取得的表单ID是:"+formId);
						List<FormField> formFields = fieldsDAO.jsonStringToList(
								news.getId(), aform.getContent());
						form.addResult("fieldList", formFields);
					}catch(Exception e){
						System.out.println("自定义表单查找异常:"+e.getMessage());
					}
				}
			}
			}else{
				form.addResult("tname", "无频道");
			}
		}
		form.addResult("action", "update");
		form.addResult("news", news);
		form.addResult("typeList", typeList);
		form.addResult("type2List", type2List);
		form.addResult("typeListv", typeListv);
		form.addResult("type2Listv", type2Listv);
		
		return module.findPage("VersionEdit");
	}
	
	public Page doRemoveAttach(WebForm form, Module module) {
		String newsid = CommUtil.null2String(form.get("id"));
		if (!newsid.equals("")) {
			News anews = newsDAO.getNewsById(newsid);
			if (anews.getFile() != null) {
				String attachFile = anews.getFile();
				// String filePath=attachFile.substring(1).replace("/",
				// File.separator);
				String filePath = Globals.APP_BASE_DIR
						+ attachFile.substring(1).replace("/", File.separator);
				File f = new File(filePath);
				f.deleteOnExit();
				// 更新数据库
				anews.setFile(null);
				newsDAO.updateNews(anews);
			}
		}
		return null;
	}

	public Page doRemoveDoc(WebForm form, Module module) {
		String newsid = CommUtil.null2String(form.get("id"));
		if (!newsid.equals("")) {
			News anews = newsDAO.getNewsById(newsid);
			if (anews.getDocfile() != null) {
				String attachFile = anews.getDocfile();
				String filePath = Globals.APP_BASE_DIR
						+ attachFile.substring(1).replace("/", File.separator);
				// 先删除转换前的文件
				String originalPath = filePath.substring(0,
						filePath.lastIndexOf("."));
				System.out.println("删除文件:" + originalPath);
				File originalFile = new File(originalPath);
				if (originalFile.exists()) {
					originalFile.delete();
				}
				String pdfPath = originalPath.substring(0,
						originalPath.lastIndexOf("."))
						+ ".pdf";
				System.out.println("删除文件:" + pdfPath);
				File pdfFile = new File(pdfPath);
				if (pdfFile.exists()) {
					pdfFile.delete();
				}
				File f = new File(filePath);
				if (f.exists()) {
					f.delete();
				}
				// 更新数据库
				anews.setDocfile(null);
				newsDAO.updateNews(anews);
			}
		}
		return null;
	}

	public Page doCut(WebForm form, Module module) {
		ActionContext.getContext().getSession().removeAttribute("copyType");
		ActionContext.getContext().getSession().removeAttribute("copyID");
		String cutID = CommUtil.null2String(form.get("targetid"));
		if (cutID.length() > 0) {
			ActionContext.getContext().getSession()
					.setAttribute("copyType", "cut");
			ActionContext.getContext().getSession()
					.setAttribute("copyID", cutID);
		}
		return null;
	}

	public Page doCopy(WebForm form, Module module) {
		ActionContext.getContext().getSession().removeAttribute("copyType");
		ActionContext.getContext().getSession().removeAttribute("copyID");
		String copyID = CommUtil.null2String(form.get("targetid"));
		if (copyID.length() > 0) {
			ActionContext.getContext().getSession()
					.setAttribute("copyType", "copy");
			ActionContext.getContext().getSession()
					.setAttribute("copyID", copyID);
		}
		return null;
	}

	public Page doLink(WebForm form, Module module) {
		ActionContext.getContext().getSession().removeAttribute("copyType");
		ActionContext.getContext().getSession().removeAttribute("copyID");
		String copyID = CommUtil.null2String(form.get("targetid"));
		if (copyID.length() > 0) {
			ActionContext.getContext().getSession()
					.setAttribute("copyType", "link");
			ActionContext.getContext().getSession()
					.setAttribute("copyID", copyID);
		}
		return null;
	}

	public Page doPaste(WebForm form, Module module) {
		String copyType = ActionContext.getContext().getSession()
				.getAttribute("copyType").toString();
		String copyID = ActionContext.getContext().getSession()
				.getAttribute("copyID").toString();
		String typeid = CommUtil.null2String(form.get("tid"));
		String treenews = CommUtil.null2String(form.get("treenews"));
		//System.out.println("取得的treenews:" + treenews);
		if (copyType.equals("cut")) {
			if (copyID.length() > 0) {
				if (copyID.indexOf(",") > 0) {
					String[] ids = copyID.split(",");
					for (int i = 0; i < ids.length; i++) {
						News news = newsDAO.getNewsById(ids[i]);
						if (!typeid.equals(news.getType())
								|| !treenews.equals(news.getTreenews())) {
							news.setType(typeid);
							if (treenews.length() > 0) {
								news.setTreenews(treenews);
							}
							newsDAO.updateNews(news);
						}
					}
				} else {
					News news = newsDAO.getNewsById(copyID);
					if (!typeid.equals(news.getType())
							|| !treenews.equals(news.getTreenews())) {
						news.setType(typeid);
						if (treenews.length() > 0) {
							news.setTreenews(treenews);
						}
						newsDAO.updateNews(news);
					}
				}
			}
		} else if (copyType.equals("copy")) {
			if (copyID.length() > 0) {
				if (copyID.indexOf(",") > 0) {
					String[] ids = copyID.split(",");
					for (int i = 0; i < ids.length; i++) {
						News news = newsDAO.getNewsById(ids[i]);
						com.knife.news.model.News anew = new com.knife.news.model.News();
						String newid = anew.getId();
						anew.setNews(news);
						if (!typeid.equals(anew.getType())
								|| !treenews.equals(news.getTreenews())) {
							anew.setId(newid);
							anew.setType(typeid);
							if (treenews.length() > 0) {
								news.setTreenews(treenews);
							}
							News anews = new News(anew);
							newsDAO.saveNews(anews);
						}
					}
				} else {
					News news = newsDAO.getNewsById(copyID);
					com.knife.news.model.News anew = new com.knife.news.model.News();
					String newid = anew.getId();
					anew.setNews(news);
					if (!typeid.equals(anew.getType())
							|| !treenews.equals(news.getTreenews())) {
						anew.setId(newid);
						anew.setType(typeid);
						if (treenews.length() > 0) {
							news.setTreenews(treenews);
						}
						News anews = new News(anew);
						newsDAO.saveNews(anews);
					}
				}
			}
		} else if (copyType.equals("link")) {
			if (copyID.length() > 0) {
				if (copyID.indexOf(",") > 0) {
					String[] ids = copyID.split(",");
					for (int i = 0; i < ids.length; i++) {
						News news = newsDAO.getNewsById(ids[i]);
						com.knife.news.model.News anew = new com.knife.news.model.News();
						String newid = anew.getId();
						// anew.setNews(news);
						if (!typeid.equals(anew.getType())
								|| !treenews.equals(news.getTreenews())) {
							anew.setId(newid);
							anew.setTitle(news.getTitle());
							anew.setType(typeid);
							anew.setLink(news.getId());
							anew.setContent("<p>&nbsp;</p>");
							anew.setCommend("0");
							anew.setDisplay(1);
							if (treenews.length() > 0) {
								anew.setTreenews(treenews);
							}
							anew.setDate(new Date());
							News anews = new News(anew);
							newsDAO.saveNews(anews);
						}
					}
				} else {
					News news = newsDAO.getNewsById(copyID);
					com.knife.news.model.News anew = new com.knife.news.model.News();
					String newid = anew.getId();
					// anew.setNews(news);
					if (!typeid.equals(anew.getType())
							|| !treenews.equals(news.getTreenews())) {
						anew.setId(newid);
						anew.setTitle(news.getTitle());
						anew.setType(typeid);
						anew.setLink(news.getId());
						anew.setContent("<p>&nbsp;</p>");
						anew.setCommend("0");
						anew.setDisplay(1);
						if (treenews.length() > 0) {
							anew.setTreenews(treenews);
						}
						anew.setDate(new Date());
						News anews = new News(anew);
						newsDAO.saveNews(anews);
					}
				}
			}
		}
		return null;
	}

	public Page doRename(WebForm form, Module module) {
		return null;
	}

	public Page doDelete(WebForm form, Module module) {
		return null;
	}

	// 删除上传类型字段
	public Page doRemoveField(WebForm form, Module module) {
		// String newsid=CommUtil.null2String(form.get("id"));
		String fieldid = CommUtil.null2String(form.get("fieldid"));

		if (!fieldid.equals("")) {
			Fields afield = fieldDAO.getFieldsById(fieldid);
			;
			if (afield.getValue() != null) {
				String attachFile = afield.getValue();
				// String
				// filePath=attachFile.substring(1).replace("/",File.separator);
				String filePath = Globals.APP_BASE_DIR
						+ attachFile.substring(1).replace("/", File.separator);
				File f = new File(filePath);
				if (f.exists()) {
					f.delete();
				}
				// 更新数据库
				afield.setValue(null);
				fieldDAO.updateFields(afield);
			}
		}
		return null;
	}
}
